package fi.foyt.cs.oauth;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Preference;
import org.restlet.ext.freemarker.ContextTemplateLoader;
import org.restlet.ext.freemarker.TemplateRepresentation;
import org.restlet.ext.oauth.provider.data.Client;
import org.restlet.representation.EmptyRepresentation;
import org.restlet.representation.Representation;

import fi.foyt.cs.Scope;
import fi.foyt.cs.Settings;
import fi.foyt.cs.controller.OAuthController;
import fi.foyt.cs.persistence.domainmodel.oauth.AuthorizedClient;
import freemarker.template.Configuration;

public class AuthPageServerResource extends org.restlet.ext.oauth.provider.AuthPageServerResource {

  @Override
  protected Representation getPage(String authPage) {
    OAuthController oAuthController = new OAuthController();
    
    String clientId = getQuery().getFirstValue("client");
    
    AuthorizedClient authorizedClient = oAuthController.findAuthorizedClientByClientId(clientId);
    if (!authorizedClient.getAutoAcceptScopes()) {
      Client client = clients.findById(clientId);
      String[] scopes = getQuery().getValuesArray("scope");
      String[] previousScopes = getQuery().getValuesArray("grantedScope");
  
      Configuration config = new Configuration();
      ContextTemplateLoader ctl = new ContextTemplateLoader(getContext(), Settings.getServerUrl());
      config.setTemplateLoader(ctl);
      config.setLocale(getLocale());
  
      TemplateRepresentation result = new TemplateRepresentation(authPage, config, MediaType.TEXT_HTML);
  
      HashMap<String, Object> data = new HashMap<String, Object>();
  
      
      data.put("target", "/oauth/auth_page");
      data.put("clientName", client.getApplicationName());
      data.put("requestingScopes", scopes);
      data.put("grantedScopes", previousScopes);
  
      result.setDataModel(data);
    
      return result;
    } else {
      Scope[] scopes = Scope.values();
      int i = 0;
      String[] stringScopes = new String[scopes.length];
      
      for (Scope scope : scopes) {
        stringScopes[i++] = scope.getIntenal();
      }
      
      handleAction("Accept", stringScopes);
      
      return new EmptyRepresentation();
    }
  }
  
  private Locale getLocale() {
    List<Locale> supportedLocales = Settings.getSupportedLocales();
    
    List<Preference<Language>> preferedLanguages = getRequest().getClientInfo().getAcceptedLanguages();
    for (Preference<Language> preferedLanguage : preferedLanguages) {
      Language langauge = preferedLanguage.getMetadata();
      
      for (Locale supportedLocale : supportedLocales) {
        if (supportedLocale.getLanguage().equals(langauge.getName()))
          return supportedLocale;
      }
    }
    
    return Settings.getDefaultLocale();
  }
}
